package com.hospital.servlet;

import com.hospital.dao.QueueRecordDAO;
import com.hospital.model.QueueRecord;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(urlPatterns = {
    "/queue",
    "/api/queue/current",
    "/api/queue/current/*",
    "/api/queue/waiting/*",
    "/api/queue/call/*",
    "/api/queue/complete/*",
    "/api/queue/cancel/*"
})
public class QueueServlet extends HttpServlet {
    private QueueRecordDAO queueRecordDAO = new QueueRecordDAO();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        
        String pathInfo = request.getServletPath();
        
        if (pathInfo.equals("/queue")) {
            // 处理取号请求
            handleQueueRequest(request, response, out);
        } else if (pathInfo.startsWith("/api/queue/call/")) {
            // 处理叫号请求
            handleCallRequest(request, response, out);
        } else if (pathInfo.startsWith("/api/queue/complete/")) {
            // 处理完成就诊请求
            handleCompleteRequest(request, response, out);
        } else if (pathInfo.startsWith("/api/queue/cancel/")) {
            // 处理取消就诊请求
            handleCancelRequest(request, response, out);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        
        String pathInfo = request.getServletPath();
        
        if (pathInfo.equals("/api/queue/current")) {
            // 获取所有科室当前叫号情况
            handleCurrentQueueStatus(request, response, out);
        } else if (pathInfo.startsWith("/api/queue/current/")) {
            // 获取指定医生当前就诊患者
            handleDoctorCurrentQueue(request, response, out);
        } else if (pathInfo.startsWith("/api/queue/waiting/")) {
            // 获取指定医生等待队列
            handleDoctorWaitingQueue(request, response, out);
        }
    }
    
    private void handleQueueRequest(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
        try {
            String patientName = request.getParameter("patientName");
            String patientPhone = request.getParameter("patientPhone");
            Integer departmentId = Integer.parseInt(request.getParameter("departmentId"));
            Integer doctorId = Integer.parseInt(request.getParameter("doctorId"));
            
            // 生成队列号码
            String queueNumber = queueRecordDAO.generateQueueNumber(departmentId, doctorId);
            if (queueNumber == null) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.print("{\"success\":false,\"message\":\"生成队列号码失败\"}");
                return;
            }
            
            // 创建排队记录
            QueueRecord record = new QueueRecord();
            record.setPatientName(patientName);
            record.setPatientPhone(patientPhone);
            record.setDepartmentId(departmentId);
            record.setDoctorId(doctorId);
            record.setQueueNumber(queueNumber);
            record.setStatus(0); // 等待中
            
            boolean success = queueRecordDAO.create(record);
            if (success) {
                out.print("{\"success\":true,\"queueNumber\":\"" + queueNumber + "\"}");
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.print("{\"success\":false,\"message\":\"创建排队记录失败\"}");
            }
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.print("{\"success\":false,\"message\":\"" + e.getMessage() + "\"}");
        }
    }
    
    private void handleCallRequest(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
        try {
            String[] splits = request.getServletPath().split("/");
            Integer doctorId = Integer.parseInt(splits[splits.length - 1]);
            
            // 检查是否有正在就诊的患者
            QueueRecord current = queueRecordDAO.findCurrentByDoctor(doctorId);
            if (current != null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                out.print("{\"success\":false,\"message\":\"还有患者正在就诊\"}");
                return;
            }
            
            // 获取等待队列中的第一位患者
            List<QueueRecord> waiting = queueRecordDAO.findWaitingByDoctor(doctorId);
            if (waiting.isEmpty()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                out.print("{\"success\":false,\"message\":\"暂无等待患者\"}");
                return;
            }
            
            // 更新患者状态为就诊中
            QueueRecord next = waiting.get(0);
            boolean success = queueRecordDAO.updateStatus(next.getId(), 1);
            if (success) {
                out.print("{\"success\":true}");
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.print("{\"success\":false,\"message\":\"更新状态失败\"}");
            }
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.print("{\"success\":false,\"message\":\"" + e.getMessage() + "\"}");
        }
    }
    
    private void handleCompleteRequest(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
        try {
            String[] splits = request.getServletPath().split("/");
            Integer queueId = Integer.parseInt(splits[splits.length - 1]);
            
            boolean success = queueRecordDAO.updateStatus(queueId, 2);
            if (success) {
                out.print("{\"success\":true}");
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.print("{\"success\":false,\"message\":\"更新状态失败\"}");
            }
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.print("{\"success\":false,\"message\":\"" + e.getMessage() + "\"}");
        }
    }
    
    private void handleCancelRequest(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
        try {
            String[] splits = request.getServletPath().split("/");
            Integer queueId = Integer.parseInt(splits[splits.length - 1]);
            
            boolean success = queueRecordDAO.updateStatus(queueId, 3);
            if (success) {
                out.print("{\"success\":true}");
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.print("{\"success\":false,\"message\":\"更新状态失败\"}");
            }
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.print("{\"success\":false,\"message\":\"" + e.getMessage() + "\"}");
        }
    }
    
    private void handleCurrentQueueStatus(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
        try {
            QueueRecord current = null;
            List<QueueRecord> waiting = null;
            
            // 这里可以根据需要获取所有科室的当前叫号情况
            // 暂时只返回空数据结构
            out.print("{\"current\":null,\"waiting\":[]}");
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.print("{\"error\":\"" + e.getMessage() + "\"}");
        }
    }
    
    private void handleDoctorCurrentQueue(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
        try {
            String[] splits = request.getServletPath().split("/");
            Integer doctorId = Integer.parseInt(splits[splits.length - 1]);
            
            QueueRecord current = queueRecordDAO.findCurrentByDoctor(doctorId);
            if (current != null) {
                writeQueueRecordJson(out, current);
            } else {
                out.print("null");
            }
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.print("{\"error\":\"" + e.getMessage() + "\"}");
        }
    }
    
    private void handleDoctorWaitingQueue(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
        try {
            String[] splits = request.getServletPath().split("/");
            Integer doctorId = Integer.parseInt(splits[splits.length - 1]);
            
            List<QueueRecord> waiting = queueRecordDAO.findWaitingByDoctor(doctorId);
            out.print("[");
            for (int i = 0; i < waiting.size(); i++) {
                writeQueueRecordJson(out, waiting.get(i));
                if (i < waiting.size() - 1) {
                    out.print(",");
                }
            }
            out.print("]");
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.print("{\"error\":\"" + e.getMessage() + "\"}");
        }
    }
    
    private void writeQueueRecordJson(PrintWriter out, QueueRecord record) {
        out.print("{");
        out.print("\"id\":" + record.getId() + ",");
        out.print("\"patientName\":\"" + record.getPatientName() + "\",");
        out.print("\"patientPhone\":\"" + record.getPatientPhone() + "\",");
        out.print("\"queueNumber\":\"" + record.getQueueNumber() + "\",");
        out.print("\"status\":" + record.getStatus() + ",");
        out.print("\"department\":{");
        out.print("\"id\":" + record.getDepartment().getId() + ",");
        out.print("\"name\":\"" + record.getDepartment().getName() + "\"");
        out.print("},");
        out.print("\"doctor\":{");
        out.print("\"id\":" + record.getDoctor().getId() + ",");
        out.print("\"name\":\"" + record.getDoctor().getName() + "\",");
        out.print("\"title\":\"" + (record.getDoctor().getTitle() != null ? record.getDoctor().getTitle() : "") + "\"");
        out.print("},");
        out.print("\"waitingTime\":\"" + calculateWaitingTime(record) + "\"");
        out.print("}");
    }
    
    private String calculateWaitingTime(QueueRecord record) {
        long waitingTimeInMinutes = (System.currentTimeMillis() - record.getCreatedAt().getTime()) / (60 * 1000);
        if (waitingTimeInMinutes < 60) {
            return waitingTimeInMinutes + "分钟";
        } else {
            long hours = waitingTimeInMinutes / 60;
            long minutes = waitingTimeInMinutes % 60;
            return hours + "小时" + (minutes > 0 ? minutes + "分钟" : "");
        }
    }
}